package com.example.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Slf4j
@EnableAsync
// 默认单线程执行 -- 如果要并发执行，则需要配置线程池， 结合@Async一起使用
// 避免长调度任务阻塞短调度任务， 导致短调度任务延迟执行
@EnableScheduling
@SpringBootApplication
public class Example {

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.initialize();
        return executor;
    }

    @Bean
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) ->
                log.info("异步任务异常:{},方法名：{}，参数：{}",
                        ex.getMessage(), method.getName(), params);
    }

    public static void main(String[] args) {
        SpringApplication.run(Example.class, args);
    }
}
